package cool.taomu.toolkit.service.centre.kademlia.service

import com.google.gson.Gson
import com.google.inject.Inject
import cool.taomu.toolkit.service.centre.kademlia.utils.ServiceCentreClientPool
import cool.taomu.toolkit.service.kademlia.entity.FindNodeEntity
import cool.taomu.toolkit.service.kademlia.entity.KPeerNode
import cool.taomu.toolkit.utils.ByteBufferUtils
import java.nio.charset.StandardCharsets
import java.util.List
import java.util.function.Function
import org.slf4j.LoggerFactory
import com.google.gson.reflect.TypeToken

/**
 * 远程节点查找
 */
class FindNodeServiceFunc implements Function<FindNodeEntity, List<KPeerNode>> {
    val static LOG = LoggerFactory.getLogger(FindNodeServiceFunc);

    @Inject
    ServiceCentreClientPool clientPool;

    override apply(FindNodeEntity t) {
        var opl = clientPool.peerClient(t.node, t.localNode, [ client |
            LOG.info("向节点：{}，请求findNode 操作 nodeid ：{}", t.node, t.nodeId)
            var resp = client.findNode(t.nodeId, t.excludeIds);
            LOG.info("请求结果 ：{}", resp)
            if (resp.status == 200) {
                var data = ByteBufferUtils.toString(resp.data, StandardCharsets.UTF_8)
                return new Gson().fromJson(data, new TypeToken<List<KPeerNode>>() {
                });
            }
            return null
        ])
        if (opl.present) {
            return opl.get()
        }
        return null;

    }

}
